import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store'

// const baseURL = 'http://192.168.10.6:8888/oauth'
// const baseURL = 'http://192.168.10.6:8880'
const baseURL = '/api'

const instance = axios.create({
  baseURL,
  timeout: 5000,
})

// 请求拦截器 【登录拦截是否携带toke】
instance.interceptors.request.use(
  (config) => {
    if (config.url === '/token') {
      config.baseURL = 'http://192.168.10.6:8888/oauth'
    }

    // 检测是否携带token
    const token = useUserStore().token

    if (token) {
      // 添加请求头
      config.headers['Authorization'] = `Bearer ${token}`
    }

    return config
  },
  (err) => Promise.reject(err)
)

// 响应拦截器 【解构数据，处理错误信息】
instance.interceptors.response.use(
  (res) => {
    if (res.status === 200) {
      return res.data
    } else {
      return ElMessage.error(res.statusText)
    }
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 封装请求工具函数
type Data<T> = {
  code: number
  message: string
  data: T
}

const request = <T>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
  })
}

export { instance, baseURL, request }
